package com.zr.controller;

import com.zr.controller.R.Code;
import com.zr.controller.R.Result;
import com.zr.pojo.User;
import com.zr.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

@RestController
@RequestMapping("/my")
@CrossOrigin
public class MyInfoController {
    @Autowired
    UserService userService;

   @GetMapping("/userinfo")
    public Result getUserInfo(HttpServletRequest request) {
//        System.out.println("in getuserinfo...");
        String userName = (String) request.getAttribute("userName");
        User userDB = userService.getByUserName(userName);
        return new Result(userDB != null?Code.GET_OK:Code.GET_ERR, userDB, userDB != null?"查询用户成功":"查询用户失败");
    }

    @PostMapping("/userinfo")
    public Result updateUserInfo(User user){
//        System.out.println("in update...");
        Boolean flag = userService.updateUser(user);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR, null, flag?"更新用户基本信息成功":"更新用户基本信息失败");
    }

    @PostMapping("/updatepwd")
    public Result updateUserPwd(HttpServletRequest request, String oldPwd, String newPwd){
        String userName = (String) request.getAttribute("userName");
//        System.out.println(userName);
//        System.out.println(oldPwd);
//        System.out.println(newPwd);
        Boolean flag = userService.updateUserPwd(oldPwd, newPwd, userName);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR, null, flag?"修改密码成功！":"修改密码失败，请仔细核对原密码！");
    }
//    Todo 修改头像
//    修改头像
    @PostMapping("/update/avatar")
    public Result updateUserPic(HttpServletRequest request,  String avatar){
       String userName = (String) request.getAttribute("userName");
        Boolean flag = userService.updateUserPic(avatar, userName);
        return new Result(flag?Code.UPDATE_OK:Code.UPDATE_ERR, null, flag?"修改头像成功！":"修改头像失败！");
    }
}
